package com.base.common.converter;

import java.math.RoundingMode;
import java.text.DecimalFormat;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.operamasks.faces.annotation.DefineConverter;

@DefineConverter(id = "fileSizeConverter")
public class FileSizeConverter implements Converter {

	// 1K 的字节数
	public static final int AK = 1024;
	// 1M 的字节数
	public static final int AM = 1024 * 1024;
	// 1G的字节数
	public static final int AG = 1024 * 1024 * 1024;

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		Double fileSize = 0.0d;
		try {
			fileSize = (Double) arg2;
		} catch (Exception e) {
			e.printStackTrace();
		}
		String result = "";
		DecimalFormat format = new DecimalFormat("0.00");
		format.setRoundingMode(RoundingMode.HALF_UP);

		if (fileSize < AK) {
			if (fileSize <= 5 && fileSize > 0) {
				result = "0.01K";
			} else {
				result = format.format(fileSize / AK) + "K";
			}
		} else if (fileSize >= AK && fileSize < AM) {
			result = format.format(fileSize / AK) + "K";
		} else if (fileSize >= AM && fileSize < AG) {
			result = format.format(fileSize / AM) + "M";
		} else if (fileSize >= AG) {
			result = format.format(fileSize / AG) + "G";
		}
		return result;
	}

}
